package cn.zebra.dev.admin.module.role.service.impl;

import cn.zebra.dev.admin.module.role.dao.AdminRoleDao;
import cn.zebra.dev.admin.module.role.entity.AdminRoleEntity;
import cn.zebra.dev.admin.module.role.service.AdminRoleMenuService;
import cn.zebra.dev.admin.module.role.service.AdminRoleService;
import cn.zebra.dev.ibatis.plus.service.impl.ServiceImpl;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.ibatis.plus.utils.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 后台角色
 *
 * @author runnable
 * @date 2019-09-07 17:01:00
 */
@Service
public class AdminRoleServiceImpl extends ServiceImpl<AdminRoleDao, AdminRoleEntity> implements AdminRoleService {

    @Autowired
    private AdminRoleMenuService roleMenuService;

    @Override
    public PageUtils<AdminRoleEntity> findPage(Map<String, Object> params) {
        QueryWrapper<AdminRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.apply("delete_flag = TRUE");
        wrapper.apply(params.containsKey("roleName"), "role_name = {0}", params.get("roleName"));
        wrapper.apply(params.containsKey("createId"), "create_id = {0}", params.get("createId"));
        IPage<AdminRoleEntity> page = this.page(
                new Query<AdminRoleEntity>(params).getPage(),
                wrapper
        );
        return new PageUtils<>(page);
    }

    @Override
    public Boolean saveRole(AdminRoleEntity entity, Long createId) {
        entity.setDeleteFlag(false);
        entity.setCreateId(createId);
        entity.setCreateTime(LocalDateTime.now());
        if (!save(entity)) {
            return false;
        }
        //保存角色与菜单关系
        if (!roleMenuService.saveOrUpdate(entity.getId(), entity.getMenuIdList())) {
            throw new RuntimeException("保存失败!");
        }
        return true;
    }

    @Override
    public Boolean updateRole(Long id, AdminRoleEntity entity, Long updateId) {
        entity.setDeleteFlag(false);
        entity.setUpdateId(updateId);
        entity.setUpdateTime(LocalDateTime.now());
        if (!update(entity, "id = {0}", id)) {
            return false;
        }
        //保存角色与菜单关系
        if (!roleMenuService.saveOrUpdate(id, entity.getMenuIdList())) {
            throw new RuntimeException("保存失败!");
        }
        return true;
    }

}
